package com.zjw.zy.coreui.fragment

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.app.Activity
import android.content.Intent
import com.zjw.zy.base.BaseFragment
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zjw.zy.R
import com.zjw.zy.base.BaseRecyclerAdapter
import com.zjw.zy.bean.ImageInfo
import com.zjw.zy.coreui.fragment.adapter.ImageContentAdapter
import com.zjw.zy.coreui.fragment.holder.ImageContentHolder
import com.zjw.zy.coreui.view.ImageViewContent
import com.zjw.zy.ext.*
import com.zjw.zy.utils.AnimationUtils
import com.zjw.zy.utils.PathUtils
import com.zjw.zy.utils.ResourcesUtils
import com.zjw.zy.utils.WindowUtils
import com.zjw.zy.viewmodel.ImageContentViewModel

/**
 * @author ：zhong.jw
 * @date ：Created in 2022/10/27 9:24
 *
 *
 * 浏览图片的地方
 */
class ImageContentFragment : BaseFragment() {

    companion object {
        //图片源目录
        const val IMAGE_ROOT_PATH = "IMAGE_ROOT_PATH"

        //正使用的路径
        const val IMAGE_USING_PATH = "IMAGE_SELECT_PATH"

        //挑选图片
        private val REQUEST_PHONE_IMAGE = "ImageContentFragment_REQUEST_PHONE_IMAGE".hashCode()


        //一些监听
        var sListener: FuncListener? = null
    }

    private val imageViewModel: ImageContentViewModel by viewModels()

    private val mList: RecyclerView by lazy { findViewById(R.id.image_content) }
    private val imageContent: ImageViewContent by lazy { findViewById(R.id.image_show) }
    private val funcUiGroup: LinearLayout by lazy { findViewById(R.id.image_content_func_group) }
    private val funcPickUp: ImageView by lazy { findViewById(R.id.image_content_pick) }

    private val mDeleteSet = HashSet<ImageInfo>()

    private var isEdit = false
    private var imageRootPath: String = ""
    private var usingPath: String = ""

    private val mAdapter: ImageContentAdapter by lazy {
        ImageContentAdapter(
            usingPath = usingPath,
            listener = object :
                BaseRecyclerAdapter.ItemListener<ImageContentHolder> {
                override fun onItemClick(holder: ImageContentHolder, v: View) {
                    if (isEdit) {
                        if (usingPath == holder.data.path) {
                            "不能编辑正在使用的图片".shortToast()
                            return
                        }

                        if (holder.toggleSelect()) {
                            mDeleteSet.add(holder.data)
                        } else {
                            mDeleteSet.remove(holder.data)
                        }
                    } else {
                        //放大
                        showImage(holder)
                    }
                }

                override fun onItemLongClick(holder: ImageContentHolder, v: View): Boolean {
                    if (usingPath == holder.data.path) {
                        "不能编辑正在使用的图片".shortToast()
                        return true
                    }
                    //长按进入编辑模式
                    editMode()
                    holder.setSelect(true)
                    mDeleteSet.add(holder.data)
                    return true
                }
            })
    }

    private fun showImage(holder: ImageContentHolder) {
        WindowUtils.fullMode()

        imageContent.setPosition(holder.absoluteAdapterPosition)
        imageContent.visibility = View.VISIBLE
        AnimationUtils.objectAnimationOfAlpha(imageContent, 0f, 1f).duration(200L).start()
    }

    private fun hideImageContent() {
        if (funcUiGroup.visibility == View.VISIBLE) {
            hideFuncUi()
            return
        }

        AnimationUtils.objectAnimationOfAlpha(imageContent, 1f, 0f).duration(200L).start()
        imageContent.visibility = View.GONE
        unEditMode()
    }

    private fun hideFuncUi() {
        AnimationUtils.objectAnimationOfAlpha(funcUiGroup, 1f, 0f).duration(200L).addListener(
            object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator?) {
                    funcUiGroup.visibility = View.GONE
                }
            }
        ).start()
    }

    private fun showFuncUi() {
        sListener ?: return

        funcUiGroup.visibility = View.VISIBLE
        AnimationUtils.objectAnimationOfAlpha(funcUiGroup, 0f, 1f).duration(200L).start()
    }

    override fun onPageEnter() {
        WindowUtils.TopBar.hideAllRightButton()
        WindowUtils.TopBar.showBack()
        WindowUtils.FootBar.hide()

        unEditMode()
    }

    private fun editMode() {
        isEdit = true
        mDeleteSet.clear()

        WindowUtils.TopBar.show1RightButton(ResourcesUtils.getDrawable(R.drawable.icon_undo)) {
            unEditMode()
        }

        WindowUtils.TopBar.show2RightButton(ResourcesUtils.getDrawable(R.drawable.icon_delete)) {
            if (mDeleteSet.isNotEmpty()) {
                alertConfirm(message = ResourcesUtils.getString(R.string.delete_all_confirm)) {
                    if (it) {
                        doDelete()
                    }
                }
            }
        }
    }

    private fun doDelete() {
        imageViewModel.deleteImageInfo(mDeleteSet)

        //还原非编辑模式
        unEditMode()
    }

    private fun unEditMode() {
        isEdit = false
        WindowUtils.TopBar.showBack()
        WindowUtils.TopBar.show1RightButton(ResourcesUtils.getDrawable(R.drawable.icon_edit)) {
            editMode()
        }

        WindowUtils.TopBar.show2RightButton(ResourcesUtils.getDrawable(R.drawable.icon_cramer_image)) {
            val intent = Intent(Intent.ACTION_PICK)
            intent.type = "image/*"
            //保存修改
            mainActivity().observerActivityResult(REQUEST_PHONE_IMAGE) { result, data ->
                if (result == Activity.RESULT_OK) {
                    data?.data?.apply {
                        PathUtils.transferImageToPrivatePath(this, imageRootPath)?.let { it ->
                            val image = ImageInfo(it)
                            mAdapter.notifyImageInsert(image)
                            imageContent.notifyImageInsert(image)
                            usingPath = image.path
                            mAdapter.notifyMarkUsing(image.path)
                            //选择的图片也会被当作pick-up
                            sListener?.onPickUp(image)
                        }
                    }
                } else {
                    "添加失败".shortToast()
                }
            }
            startActivityForResult(intent, REQUEST_PHONE_IMAGE)
        }
    }

    override fun onViewRestore(savedInstanceState: Bundle?) {}

    override fun onSubscribe() {
        imageViewModel.getImageInfoList().observe(this) {
            mAdapter.notifyDataWithDiff(it)
            imageContent.bindData(it, 0)
        }
    }

    override fun onBindViewListener() {

        imageContent.bindListener(object : ImageViewContent.Listener {
            override fun onSingleTapUp() {
                hideImageContent()
            }

            override fun onLongPress() {
                //展示pick图标
                showFuncUi()
            }
        })

        funcPickUp.setOnClickListener {
            usingPath = imageContent.getCurrentImagePath().path

            //更新选择
            mAdapter.notifyMarkUsing(usingPath)

            sListener?.onPickUp(imageContent.getCurrentImagePath())
        }
    }

    override fun onBindViewValue() {
        arguments?.getString(IMAGE_ROOT_PATH)?.let {
            imageRootPath = it
            imageViewModel.initRootPath(imageRootPath)
        }

        arguments?.getString(IMAGE_USING_PATH)?.let {
            usingPath = it
        }

        mList.adapter = mAdapter
        mList.layoutManager = GridLayoutManager(context, 3)
    }

    override fun onFindView(rootView: View) {

    }


    override fun onLayoutId(): Int {
        return R.layout.image_content_fragment
    }

    override fun onBackClick() {
        if (imageContent.isVisible) {
            hideImageContent()
            return
        }
        super.onBackClick()
    }

    override fun onPageExit() {

    }


    interface FuncListener {
        fun onPickUp(imageInfo: ImageInfo) {}
    }
}